#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main() {
    std::cout << "Hello" << std::endl;
    int pipe_fd[2];
    pid_t pid;
    char r_buf[4];
    int write_num;
    //int cmd;
    memset(r_buf, 0, sizeof(r_buf));
    if (pipe(pipe_fd) < 0) {
        std::cerr << "pipe create error\n" << std::endl;
        return -1;
    } else {
        if ((pid = fork()) == 0) {
            close(pipe_fd[0]);
//            close(pipe_fd[1]);
//            sleep(10);
            std::cout << "child process\tpid:" << pid << "\tgetpid:" << getpid() << "\tgetppid:" << getppid() << std::endl; 
            if (read(pipe_fd[0], r_buf, 4) == -1) {
                std::cerr << "pipe read error" << std::endl;
            } else {
                printf("pipe read rbuf:%s", r_buf);
            }
            exit(0);
        } else if (pid > 0) {
//            sleep(1);
//            close(pipe_fd[0]);
            std::cout << "parent process\tpid:" << pid << "\tgetpid" << getpid() << "\tgetppid:" << getppid() << std::endl; 
            const char* w_buf = "111";
            if ((write_num = write(pipe_fd[1], w_buf, 2)) == -1) {
                std::cerr << "write to pipe error" << std::endl;
            } else {
                std::cout << "the bytes write to pipe is " << write_num << std::endl;
            } 
            sleep(1);
        }
    }
    return 0;
}
